package com.yanghui.lingYueBot.functions.APIBasedFunc;

import com.alibaba.fastjson.JSONObject;
import com.yanghui.lingYueBot.utils.Logger;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.Objects;

/**
 * 发送一条随机motto
 */
public class SendRandMotto {

    private static final String URL = "https://v1.hitokoto.cn/?c=d&c=i&encode=json";

    public static synchronized String getRandMotto() throws NullPointerException {
        JSONObject motto = getMottoObject();
        Objects.requireNonNull(motto);
        String mottoContent = motto.getString("hitokoto");
        String fromWho = motto.getString("from_who");
        String from = motto.getString("from");
        return (mottoContent + "\n ——" + fromWho + " " + from).replace("null", "");
    }

    private static JSONObject getMottoObject() throws NullPointerException {
        Logger.logDebug("Motto", "Get Random Motto -> Run");
        String result = null;
        OkHttpClient client = new OkHttpClient();
        Request request;
        Logger.logDebug("Motto", "Request URL >> " + URL);
        request = new Request.Builder().url(URL).get().build();
        Response response = null;
        String JSON = null;
        try {
            response = client.newCall(request).execute();
            Logger.logDebug("Motto", "Request Response >> " + response);

            JSON = Objects.requireNonNull(response.body()).string();
            result = JSON;

        } catch (IOException e) {
            Logger.logError(e);
            return null;
        }
        /* Close. */
        Objects.requireNonNull(response.body()).close();
        return com.alibaba.fastjson.JSON.parseObject(result);
    }
}
